<template>
  <div class="travel-query">
    <div class="body">
      <div ref="map" class="map" style="width:100%;height:100%;" />
    </div>
    <label for="speed">
      speed:&nbsp;
      <input id="speed" type="range" min="10" max="999" step="10" value="60">
    </label>
    <button id="start-animation">Start Animation</button>
  </div>
</template>

<script>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';

import TileLayer from 'ol/layer/Tile';
// import VectorLayer from 'ol/layer/Vector';
import XYZ from 'ol/source/XYZ';
import Feature from 'ol/Feature';
// import MultiLineString from 'ol/geom/MultiLineString';
import LineString from 'ol/geom/LineString';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import axios from 'axios';
import { fromLonLat, toLonLat } from 'ol/proj.js';
import {
  Circle as CircleStyle,
  Fill,
  Icon,
  Stroke,
  Style
} from 'ol/style';
import Point from 'ol/geom/Point';
import {getVectorContext} from 'ol/render';
// import Control from 'ol/control/Control';
// import Zoom from 'ol/control/Zoom';
export default {
  data() {
    return {
      map: null
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      const center = fromLonLat([113.132783, 27.828862]);
      console.log(center);
      const _this = this;
      
      const TDDLayer = new TileLayer({
        source: new XYZ({
          url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
        })
        // zIndex: 1
      });

      this.map = new Map({
        target: _this.$refs.map, // 地图容器
        layers: [TDDLayer],
        view: new View({
          projection: 'EPSG:4326',
          center: [113.132783, 27.828862],
          zoom: 8
        }),
        logo: false
      });

      axios.get('http://localhost:3000/gps/').then(res => {
        const data = res.data.data;
        const lngLatArr = data.map(item => {
          return toLonLat(fromLonLat([item.geoLng, item.geoLat]));
        });
        console.log(JSON.stringify(lngLatArr));
        const route = new LineString(lngLatArr);
        var feature = new Feature({
          type: 'route',
          geometry: route
        });
        const startMarker = new Feature({
          type: 'icon',
          geometry: new Point(route.getFirstCoordinate())
        });
        const endMarker = new Feature({
          type: 'icon',
          geometry: new Point(route.getLastCoordinate())
        });
        const position = startMarker.getGeometry().clone();
        const geoMarker = new Feature({
          type: 'geoMarker',
          geometry: position
        });
        const styles = {
          'route': new Style({
            stroke: new Stroke({
              width: 6,
              color: [237, 112, 0, 0.8]
            })
          }),
          'icon': new Style({
            image: new Icon({
              anchor: [0.5, 1],
              src: 'data/icon.png'
            })
          }),
          'geoMarker': new Style({
            image: new CircleStyle({
              radius: 7,
              fill: new Fill({ color: 'black' }),
              stroke: new Stroke({
                color: 'white',
                width: 2
              })
            })
          })
        };
        const linelayer = new VectorLayer({
          source: new VectorSource({
            features: [feature, geoMarker, startMarker, endMarker]
          }),
          style: function(feature) {
            return styles[feature.get('type')];
          }
        });
        this.map.addLayer(linelayer);

        const speedInput = document.getElementById('speed');
        const startButton = document.getElementById('start-animation');
        let animating = false;
        let distance = 0;
        let lastTime;

        function moveFeature(event) {
          const speed = Number(speedInput.value);
          const time = event.frameState.time;
          const elapsedTime = time - lastTime;
          distance = (distance + (speed * elapsedTime) / 1e6) % 2;
          lastTime = time;

          const currentCoordinate = route.getCoordinateAt(
            distance > 1 ? 2 - distance : distance
          );
          position.setCoordinates(currentCoordinate);
          const vectorContext = getVectorContext(event);
          vectorContext.setStyle(styles.geoMarker);
          vectorContext.drawGeometry(position);
          // tell OpenLayers to continue the postrender animation
          _this.map.render();
        }

        function startAnimation() {
          animating = true;
          lastTime = Date.now();
          startButton.textContent = 'Stop Animation';
          linelayer.on('postrender', moveFeature);
          // hide geoMarker and trigger map render through change event
          geoMarker.setGeometry(null);
        }

        function stopAnimation() {
          animating = false;
          startButton.textContent = 'Start Animation';

          // Keep marker at current animation position
          geoMarker.setGeometry(position);
          linelayer.un('postrender', moveFeature);
        }

        startButton.addEventListener('click', function () {
          if (animating) {
            stopAnimation();
          } else {
            startAnimation();
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";
$moduleBoxShadow: 0px 0px 5px 0px rgba(39, 51, 77, 0.2);
$searchBoxHeight: 150px;
$planBoxHeight: 86px;
$titleHeight:20px;
$psHeight:20px;
  .travel-query{
    width: 100%;
    height: 100%;
    position: relative;
  }

  .body{
    height: 90%;
    position: relative;
  }

</style>
